package com.hwl.security.handler;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenManager {
    private final String tokenSignKey = "guli";

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public String getUserFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(tokenSignKey)
                .parseClaimsJws(token).getBody()
                .getSubject();
    }

    /**
     * 生成token过期时间
     */
    private Date generateExpirationDate() {
        long tokenExpiration = 24 * 60 * 60 * 1000;
        return new Date(System.currentTimeMillis() + tokenExpiration);
    }
}
